<?php

namespace App\Services;

use App\Contract\RedisKey;
use App\Exceptions\GeneralException;
use App\Models\Setting;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;

class SettingService
{

    public function updateSingleSetting(string $key, string $value)
    {
        $setting = Setting::query()->where('key', $key)->first();
        $setting->value = $value;
        $setting->save();
        $redisKey = RedisKey::SETTING_HASH;
        $cacheValue = Redis::hGet($redisKey, $key);
        $cacheValue = json_decode($cacheValue, true);
        $cacheValue['value'] = $value;
        $cacheValue = json_encode($cacheValue);
        Redis::hSet($redisKey, $key, $cacheValue);
        return true;
    }

    public function getAllSetting()
    {
        $redisKey = RedisKey::SETTING_HASH;
        $res = Redis::hGetAll($redisKey);
        $return = [];
        if (empty($res)) {
            $res = Setting::query()->orderBy('key')->get();
            foreach ($res as $key => $val) {
                $return[$val->key] = $val;
                Redis::hSet($redisKey, $val->key, json_encode($val));
            }
        } else {
            foreach ($res as $key => $val) {
                $return[$key] = json_decode($val, true);
            }
        }
        return $return;
    }

    public function getSetting(string $key)
    {
        $redisKey = RedisKey::SETTING_HASH;
        $cache = Redis::hGet($redisKey, $key);
        if (!$cache) {
            $setting = Setting::query()->where('key', $key)->first();
            if (!$setting) {
                customLog("设置选项{$key}键值不存在");
                throw new GeneralException('服务异常[29381]');
            }
            Redis::hSet($redisKey, $key, json_encode($setting));
            $res = $setting->value;
        } else {
            customLog("redis 拿出来的缓存：{$key},内容{$cache}");
            $decode = json_decode($cache, true);
            $res = $decode['value'];
        }
        return $res;
    }
}
